package com.example.gmallproduct.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.common.constant.ProductConstant;
import com.example.gmallproduct.VO.AttrResponseVo;
import com.example.gmallproduct.VO.AttrVo;

import com.example.gmallproduct.dao.AttrAttrgroupRelationDao;
import com.example.gmallproduct.dao.AttrGroupDao;
import com.example.gmallproduct.dao.CategoryDao;
import com.example.gmallproduct.entity.AttrAttrgroupRelationEntity;
import com.example.gmallproduct.entity.AttrGroupEntity;
import com.example.gmallproduct.entity.CategoryEntity;
import com.example.gmallproduct.service.AttrAttrgroupRelationService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.common.utils.PageUtils;
import com.common.utils.Query;

import com.example.gmallproduct.dao.AttrDao;
import com.example.gmallproduct.entity.AttrEntity;
import com.example.gmallproduct.service.AttrService;


@Service("attrService")
public class AttrServiceImpl extends ServiceImpl<AttrDao, AttrEntity> implements AttrService {


    @Autowired
    private AttrAttrgroupRelationService ataService;

    @Autowired
    private AttrAttrgroupRelationDao ataDao;

    @Autowired
    private AttrGroupDao attrGroupDao;

    @Autowired
    private AttrDao attrDao;

    @Autowired
    private CategoryDao categoryDao;


    @Override
    public PageUtils findNoAttr(Map<String, Object> params, Long attrgroupId) {
        //1、当前分组只能关联自己所属的分类里面的所有属性
        AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(attrgroupId);
        Long catelogId = attrGroupEntity.getCatelogId();
        //2、当前分组只能关联别的分组没有引用的属性
        //2.1)、当前分类下的其他分组
        List<AttrGroupEntity> group = attrGroupDao.selectList(new QueryWrapper<AttrGroupEntity>().eq("catelog_id", catelogId));
        List<Long> collect = group.stream().map(item -> {
            return item.getAttrGroupId();
        }).collect(Collectors.toList());

        //2.2)、这些分组关联的属性
        List<AttrAttrgroupRelationEntity> groupId = ataDao.selectList(new QueryWrapper<AttrAttrgroupRelationEntity>().in("attr_group_id", collect));
        List<Long> attrIds = groupId.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());

        //2.3)、从当前分类的所有属性中移除这些属性；
        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelogId).eq("attr_type", ProductConstant.ATTR_BASE.getCode());
        if (attrIds != null && attrIds.size() > 0) {
            wrapper.notIn("attr_id", attrIds);
        }
        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            wrapper.and((w) -> {
                w.eq("attr_id", key).or().like("attr_name", key);
            });
        }
        IPage<AttrEntity> page = this.page(new Query<AttrEntity>().getPage(params), wrapper);

        PageUtils pageUtils = new PageUtils(page);

        return pageUtils;
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params),
                new QueryWrapper<AttrEntity>()
        );

        return new PageUtils(page);
    }

    @Override
    public void saveCaseCade(AttrVo attr) {
        AttrEntity attrEntity = new AttrEntity();
        BeanUtils.copyProperties(attr, attrEntity);
        this.save(attrEntity);
        AttrAttrgroupRelationEntity entity = new AttrAttrgroupRelationEntity();
        //只有基本属性才更新关联表
        if (attr.getAttrType() == ProductConstant.ATTR_BASE.getCode()) {
            //级联保存到attr-attrgroup-relation表中
            entity.setAttrId(attrEntity.getAttrId());
            entity.setAttrGroupId(attr.getAttrGroupId());
            ataService.save(entity);
        }
    }

    @Override
    public PageUtils queryPageByCatId(Map<String, Object> map, Long catId, String attrType) {
        String key = (String) map.get("key");
        QueryWrapper<AttrEntity> queryWrapper = new QueryWrapper<AttrEntity>();
        if (attrType.equalsIgnoreCase("base")) {
            queryWrapper.eq("attr_type", ProductConstant.ATTR_BASE.getCode());
        } else if (attrType.equalsIgnoreCase("sale")) {
            queryWrapper.eq("attr_type", ProductConstant.ATTR_SALE.getCode());
        }


        if (key != null && key.length() > 0 && catId != 0) {
            //有关键字,有key
            queryWrapper.eq("catelog_id", catId).and((item) -> {
                item.like("attr_name", key);
            });
        } else if (catId == 0 && key != null && key.length() > 0) {
            //有关键字,没有catid
            queryWrapper.eq("catelog_id", key).or().like("attr_name", key);
        } else if (catId != 0 && key != null && key.length() <= 0) {
            //有catid,没有key
            queryWrapper.eq("catelog_id", catId);
        }
        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(map),
                queryWrapper
        );
        PageUtils pageUtils = new PageUtils(page);
        List<AttrEntity> records = page.getRecords();
        List<AttrResponseVo> list = records.stream().map((entity) -> {
            AttrResponseVo vo = new AttrResponseVo();
            BeanUtils.copyProperties(entity, vo);

            //查groupName
            AttrAttrgroupRelationEntity relationEntity = ataDao.selectOne(new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", entity.getAttrId()));
            if (relationEntity != null) {
                Long groupId = relationEntity.getAttrGroupId();
                if (groupId != null) {
                    AttrGroupEntity attrGroupEntity = attrGroupDao.selectById(groupId);
                    if (attrGroupEntity != null) {
                        vo.setGroupName(attrGroupEntity.getAttrGroupName());
                    }
                }
            }
            //查categoryName
            Long catelogId = entity.getCatelogId();
            if (catelogId != null) {
                CategoryEntity categoryEntity = categoryDao.selectById(catelogId);
                if (categoryEntity != null) {
                    vo.setCatelogName(categoryEntity.getName());
                }
            }
            return vo;
        }).collect(Collectors.toList());
        pageUtils.setList(list);
        return pageUtils;
    }

    @Override
    public AttrResponseVo findDetail(Long attrId) {
        AttrEntity byId = this.getById(attrId);
        AttrResponseVo vo = new AttrResponseVo();
        BeanUtils.copyProperties(byId, vo);
        Long catelogId = byId.getCatelogId();
        ArrayList<Long> list = new ArrayList();
        findPath(catelogId, list);
        Long[] longs = new Long[list.size()];
        int j = list.size() - 1;
        for (int i = 0; i < list.size(); i++) {
            longs[i] = list.get(j--);
        }
        vo.setCatelogPath(longs);
        return vo;
    }

    @Override
    public void updateCaseCade(AttrVo attr) {
        AttrEntity entity = new AttrEntity();
        BeanUtils.copyProperties(attr, entity);
        //更新attr基本信息
        attrDao.update(entity, new UpdateWrapper<AttrEntity>().eq("attr_id", entity.getAttrId()));
        //更新分组关联信息
        AttrAttrgroupRelationEntity relationEntity = new AttrAttrgroupRelationEntity();
        //基本属性才更新关联表
        if (attr.getAttrType() == ProductConstant.ATTR_BASE.getCode()) {
            relationEntity.setAttrId(attr.getAttrId());
            relationEntity.setAttrGroupId(attr.getAttrGroupId());
            ataDao.update(relationEntity, new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            Long count = ataDao.selectCount(new UpdateWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attr.getAttrId()));
            if (count <= 0) {
                ataDao.insert(relationEntity);
            }
        }
    }

    @Override
    public PageUtils getBySaleList(Map<String, Object> params, Long catelodId) {

        QueryWrapper<AttrEntity> wrapper = new QueryWrapper<AttrEntity>().eq("catelog_id", catelodId);
        List<AttrEntity> entityList = attrDao.selectList(wrapper);
        List<AttrResponseVo> responseVoList = new ArrayList<>();
        for (AttrEntity attrEntity : entityList) {
            AttrResponseVo attrResponseVo = new AttrResponseVo();
            BeanUtils.copyProperties(attrEntity, attrResponseVo);
            //查groupName
            QueryWrapper<AttrAttrgroupRelationEntity> wrapper1 = new QueryWrapper<AttrAttrgroupRelationEntity>().eq("attr_id", attrEntity.getAttrId());
            AttrAttrgroupRelationEntity relationEntity = ataDao.selectOne(wrapper1);
            if (relationEntity != null) {
                QueryWrapper<AttrGroupEntity> wrapper2 = new QueryWrapper<AttrGroupEntity>().eq("attr_group_id", relationEntity.getAttrGroupId());
                AttrGroupEntity groupEntity = attrGroupDao.selectOne(wrapper2);
                if (groupEntity != null) {
                    attrResponseVo.setGroupName(groupEntity.getAttrGroupName());
                }
            }
            //查catelogName
            QueryWrapper<CategoryEntity> wrapper2 = new QueryWrapper<CategoryEntity>().eq("cat_id", attrEntity.getCatelogId());
            CategoryEntity categoryEntity = categoryDao.selectOne(wrapper2);
            if (categoryEntity != null) {
                attrResponseVo.setCatelogName(categoryEntity.getName());
            }
            responseVoList.add(attrResponseVo);
        }

        IPage<AttrEntity> page = this.page(
                new Query<AttrEntity>().getPage(params)
        );
        PageUtils pageUtils = new PageUtils(page);
        pageUtils.setList(responseVoList);
        return pageUtils;
    }

    private void findPath(Long id, ArrayList<Long> list) {
        list.add(id);
        CategoryEntity categoryEntity = categoryDao.selectById(id);
        if (categoryEntity != null && categoryEntity.getParentCid() != 0) {
            findPath(categoryEntity.getParentCid(), list);
        }
    }

}